﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace YBlog.Application.System
{
    /// <summary>
    /// 内存缓存
    /// </summary>
    [ApiDescriptionSettings("System")]
    public class MemoryCacheService : IMemoryCacheService, IDynamicApiController, ISingleton
    {
        public static Dictionary<string,object> Keys = new Dictionary<string, object>();
        private IMemoryCache _memoryCache = App.GetService<IMemoryCache>();

        /// <summary>
        /// 获取或创建内存缓存
        /// </summary>
        /// <typeparam name="TItem"></typeparam>
        /// <param name="key"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        [ApiDescriptionSettings(KeepName = true)]
        public Task<TItem> GetOrCreateAsync<TItem>(string key, Func<ICacheEntry, Task<TItem>> factory)
        {
            Keys[key] = factory;
            return _memoryCache.GetOrCreateAsync(key, factory);
        }
        /// <summary>
        /// 清空缓存
        /// </summary>
        /// <returns></returns>
        [ApiDescriptionSettings(KeepName = true)]
        public Task Clear()
        {
            Keys.Keys.ToList()
                .ForEach(key => 
            {
                _memoryCache.Remove(key);
            });
            Keys.Clear();
            return Task.CompletedTask;
        }
        /// <summary>
        /// 设置内存缓存
        /// </summary>
        /// <typeparam name="TItem"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        [ApiDescriptionSettings(KeepName = true)]
        public TItem Set<TItem>(string key, TItem value)
        {
            Keys.Add(key,null);
            return _memoryCache.Set<TItem>(key, value);
        }
        /// <summary>
        /// 获取内存缓存
        /// </summary>
        /// <typeparam name="TItem"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        [ApiDescriptionSettings(KeepName = true)]
        public TItem Get<TItem>(string key)
        {
            return _memoryCache.Get<TItem>(key);
        }
        /// <summary>
        /// 删除内存缓存
        /// </summary>
        /// <param name="key"></param>
        [ApiDescriptionSettings(KeepName = true)]
        public Task RemoveAsync(string key)
        {
            Keys.Remove(key);
            _memoryCache.Remove(key);
            return Task.CompletedTask;
        }

        public void Update(string key)
        {
            var func = Keys[key];
            Keys.Remove(key);
            _memoryCache.Remove(key);
            _memoryCache.GetOrCreateAsync(key, (Func<ICacheEntry, Task<object>>)Keys[key]);
        }
    }
}
